// Copyright 2022 The Liquigo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package translate

import (
	"strings"

	. "gitee.com/west0207/liquigo/core/log"
	utils "gitee.com/west0207/liquigo/core/utils"

	etree "gitee.com/west0207/etree"
)

// 获取sqlFile的Entity标签指定的sql文件中的全部sql语句
// dbmsName *string 数据库类型名称，例如：mysql
// sqlFileEle *etree.Element sqlFile的Entity标签
// <sqlFile dbms="!sqlite, postgres, !mysql"
// 		path="db/app01/db-app01-01.sql" />
// <sqlFile dbms="!sqlite, postgres, kingbase, oracle"
// 		path="classpath:db/app01/db-app01-01.sql" />
// <sqlFile dbms="!sqlite, postgres, mysql"
// 		path="/dev/liquigo/db/app01/db-app01-02.sql" />
func GetSqlFileSql(dbmsName *string, sqlFileEle *etree.Element) (string, error) {
	dbms := sqlFileEle.SelectAttrValue("dbms", utils.EMPTY)
	pathAttr := sqlFileEle.SelectAttrValue("path", utils.EMPTY)
	path := strings.Replace(pathAttr, "classpath:", utils.EMPTY, -1)

	if CheckDbms(dbmsName, &dbms) {
		fileBytes, err := utils.GetFileBytes(&path)
		if err != nil {
			Sug.Errorf("GetFileBytes(%v) err: %v", path, err)
			return utils.EMPTY, err
		}
		sql := string(fileBytes[:])
		// Sug.Error("sqlFile sql: \n", sql)
		return sql, nil
	}
	return utils.EMPTY, nil
}
